﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F4AssemblyWTS : Form
    {
        public int f4wtsID;
        public frm_Edit_F4AssemblyWTS()
        {
            InitializeComponent();
            this.f4wtsID = 0;
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.addDate.EditValue = DateTime.Now.Date;
            getStaffList();
            this.staffID.Properties.AutoComplete = true;            
            getWorkIDList();
            this.timeworkID.Properties.AutoComplete = true;
            getOrderNoList();
            this.orderNo.Properties.AutoComplete = true;
        }

        //////////////////////////////////////////////
        /// Load Data for selected record
        //////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;

            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT Date, StaffID, TimeWorkID, TimePlanNo, F4Time, ActualQuantity, Note"
                    + " FROM [231_TimeInput]"
                    + " WHERE ID=" + f4wtsID;                    
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    int i = 0;
                    ComboboxItem item = new ComboboxItem();
                    
                    this.addDate.EditValue = DateTime.Parse(dataReader["Date"].ToString()).Date;

                    for (i = 0; i < this.staffID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.staffID.Properties.Items[i];
                        if (item.Value.ToString().Trim() == dataReader["StaffID"].ToString().Trim())
                        {
                            this.staffID.SelectedIndex = i;
                        }
                    }

                    for (i = 0; i < this.timeworkID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.timeworkID.Properties.Items[i];
                        if (item.Value.ToString().Trim() == dataReader["TimeWorkID"].ToString().Trim())
                        {
                            this.timeworkID.SelectedIndex = i;
                        }
                    }

                    for (i = 0; i < this.orderNo.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.orderNo.Properties.Items[i];
                        if (item.Value.ToString().Trim() == dataReader["TimePlanNo"].ToString().Trim())
                        {
                            this.orderNo.SelectedIndex = i;
                        }
                    }

                    this.timeValue.Text = dataReader["F4Time"].ToString();
                    this.quantityValue.Text = dataReader["ActualQuantity"].ToString();
                    this.noteText.Text = dataReader["Note"].ToString();
                }
                else
                {
                    ret = false;
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot Load Data");
            }
            return ret;
        }
        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getOrderNoList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TimePlanNo, CompID, Quantity, FinishedDate"
                    + " FROM [231_TimePlan] WHERE FinishedDate IS NULL ORDER BY TimePlanNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    string part_no = null;
                    string finished_date = null;
                    if (dataReader["CompID"] != DBNull.Value)
                    {
                        part_no = " | " + dataReader["CompID"].ToString();
                    }
                    if (dataReader["FinishedDate"] != DBNull.Value)
                    {
                        finished_date = " | " + DateTime.Parse(dataReader["FinishedDate"].ToString()).ToShortDateString();
                    }
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TimePlanNo"].ToString() + part_no + finished_date;                    
                    item.Value = dataReader["TimePlanNo"].ToString();
                    this.orderNo.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot get OrderNo list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Staff list to form
        ////////////////////////////////////////////////
        private void getStaffList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName FROM [222_Staff] WHERE StopDate IS NULL ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString() + " | " + dataReader["StaffID"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.staffID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot get Staff list");
            }
        }

        ////////////////////////////////////////////////
        /// Load WorkID list to form
        ////////////////////////////////////////////////
        private void getWorkIDList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TimeWorkID, TimeWorkName FROM [231_TimeWork] ORDER BY TimeWorkName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TimeWorkName"].ToString() + " | " + dataReader["TimeWorkID"].ToString();
                    item.Value = dataReader["TimeWorkID"].ToString();
                    this.timeworkID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get TimeWorkID list");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            ComboboxItem staff_id = new ComboboxItem();
            ComboboxItem timework_id = new ComboboxItem();
            ComboboxItem order_no = new ComboboxItem();
            if (string.IsNullOrEmpty(error))
            {
                if (this.addDate.EditValue == null)
                {
                    error = "Please select Date";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.staffID.SelectedIndex == -1)
                {
                    error = "Please select Staff";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.timeworkID.SelectedIndex == -1)
                {
                    error = "Please select Work ID";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.orderNo.SelectedIndex == -1)
                {
                    error = "Please select Order No";
                }
            }

            float time_value = 0;
            if (string.IsNullOrEmpty(error))
            {
                bool check_time = float.TryParse(this.timeValue.Text, out time_value);
                if (!check_time)
                {
                    error = "Invalid time value";
                }
                else
                {
                    if (time_value <= 0)
                    {
                        error = "Time value must be greater than 0";
                    }
                }
            }

            int quantity = 0;
            if (string.IsNullOrEmpty(error))
            {
                bool check_quantity = Int32.TryParse(this.quantityValue.Text, out quantity);
                if (!check_quantity)
                {
                    error = "Invalid Quantity";
                }
                else
                {
                    if (quantity <= 0)
                    {
                        error = "Quantity must be greater than 0";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                staff_id = (ComboboxItem)this.staffID.SelectedItem;
                timework_id = (ComboboxItem)this.timeworkID.SelectedItem;
                order_no = (ComboboxItem)this.orderNo.SelectedItem;

                try
                {
                    DateTime inputdate;
                    DateTime.TryParse(this.addDate.DateTime.Date.ToString(), out inputdate);
                    myConnection.Open();
                    string sql = "UPDATE [231_TimeInput] SET Date=@dateinput, StaffID='" + staff_id.Value.ToString() + "',"
                        + " TimeWorkID='" + timework_id.Value.ToString() + "', TimePlanNo='" + order_no.Value.ToString() + "',"
                        + " F4Time=" + time_value + ", ActualQuantity=" + quantity + ", Note='" + this.noteText.Text + "'"
                        + " WHERE ID=" + f4wtsID;
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@dateinput", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F4 WTS updated success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot update F4 WTS. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }

    }
}
